package cn.nb12.xbox.utils;

import java.io.IOException;
import java.util.DoubleSummaryStatistics;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class GetInfo {
	public static void main(String[] args) {
		String url="https://www.microsoft.com/zh-hk/store/p/battlefield-1-they-shall-not-pass/c2m3gd4wqj2z";
		Map<String, Object> info = getInfo(url);
		System.out.println(info);
	}
	
	public static Map<String,Object> getInfo(String url) {
		String response;
		try {
			Map<String,String> headers=new HashMap<>();
			headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:57.0) Gecko/20100101 Firefox/57.0");
			headers.put("Content-Type", "application/json; charset=utf-8");
			response = RequestUtil.sendPost(url, "",headers,"UTF-8");
			Document doc = Jsoup.parse(response);
			
			Map<String,Object> data=new HashMap<>();
			
			Elements select2 = doc.select("h1[id='page-title']");//名称
			Elements select3 = doc.select("meta[name='twitter:image']");//图片
			Elements select4 = doc.select("meta[name='keywords']");//关键字
			Elements links = doc.select("div.srv_microdata");
			Elements moneySelect = doc.select("div[class='price-disclaimer'] span");//价格
			if(links!=null && links.size()>0) {
				Element element = links.get(0);
				Elements select = element.select("meta");
				if(select!=null && select.size()==2) {
					//Element currency = select.get(1);
					data.put("name", select2.text());//名称
					data.put("imgurl", select3.attr("content"));//图片
					
					DoubleSummaryStatistics summaryStatistics = moneySelect.stream()
							.filter(x->x!=null && x.text()!=null && x.text().length()>0)//不为空
							.map(x->Double.parseDouble(Utils.parse(x.text())))//获得内容
							.mapToDouble(x->x)//转数字
							.summaryStatistics();//获取结果
					String money = summaryStatistics.getMin()+"";//价格
					if(money!=null) {
						money=money.replaceAll(",", ".");
					}
					data.put("money", money);//价格
					data.put("key", select4.attr("content"));//关键字
					return data;
				}
			}
		} catch (IOException e) {
			throw new RuntimeException("获取游戏信息发生异常",e);
		}
		return null;
	}
}
